$(document).ready(function () {

    initSubMenu();
    queryTable();
    queryType()


    layui.use(function () {

        var layer = layui.layer;

        laydate = layui.laydate;

        // 表格
        form = layui.form;

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }

            new AjaxChain()
                .setUrl('/material/charge/rule/save')
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });


    });
})
var params = {};//查询条件参数
var form, unit, laydate;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID
var typeStr = '';//物资类型集合

// 查询物资类型
queryType = () => {

    new AjaxChain()
        .setUrl('/material/type/select')
        .then(data => {
            typeStr = data.reduce((x, y) => {
                return x + `<option value="${y.id}">${y.name}</option>`
            }, '<option value="">物资类型</option>')

            $('#search-type').empty().append(typeStr)

            form.render('select');
        })
        .send();
}
// 查询表格数据
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 240

    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/material/charge/rule/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'typeName', title: '物资类型', align: "center" }
                , { field: 'typeCode', title: '类型编码', align: "center" }
                , { field: 'cycleHour', title: '充电周期(小时)', align: "center" }
                , { field: 'beforeHour', title: '提前提醒(小时)', align: "center" }
                , {
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                <div onclick='tableHandle(1,${res})' class="table-edit layui-btn">
                                  <img src="../static/img/edit.png">编辑
                                </div>
                                <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/material/charge/rule/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;


        default:
            break;
    }
}



openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 1 ? "新增" : "编辑") + '充电规则',
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['30%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {
            laydate.render({
                elem: '#expiryDate',
                trigger: 'click',
            });

            if (res) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }

        },
        content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                   <div class="form-item">
                        <label class="layui-form-label">物资类型</label>
                        <div class="layui-input-block">
                            <select name="type" lay-filter="" lay-verify="required">
                                ${typeStr}
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">充电周期(小时)</label>
                        <div class="layui-input-block">
                            <input type="text" name="cycleHour"  lay-verify="required|isInt" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">提前提醒(小时)</label>
                        <div class="layui-input-block">
                            <input type="text" name="beforeHour"  lay-verify="required|isInt" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool" >
                        <button type="reset" class="layui-btn layui-btn-primary btn-reset">重置</button>
                        <button class="layui-btn" lay-submit lay-filter="edit">确认</button>
                    </div>
                </form>`
    });

}